<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>类型模板管理</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
    <link rel="stylesheet" href="/plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/plugins/adminLTE/css/AdminLTE.css">
    <link rel="stylesheet" href="/plugins/adminLTE/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="/css/style.css">
	<script src="/plugins/jQuery/jquery-2.2.3.min.js"></script>
    <script src="/plugins/bootstrap/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="/plugins/select2/select2.css" />
    <link rel="stylesheet" href="/plugins/select2/select2-bootstrap.css" />
    <script src="/plugins/select2/select2.min.js" type="text/javascript"></script>
	<script type="text/javascript" src="/bootstrap/bootstrap-table/dist/bootstrap-table.min.js"></script>
	<script type="text/javascript" src="/bootstrap/bootstrap-table/dist/locale/bootstrap-table-zh-CN.min.js"></script>
	<link rel="stylesheet" type="text/css" href="/bootstrap/bootstrap-table/dist/bootstrap-table.min.css">
	<script type="text/javascript" src="/js/toastr/toastr.min.js"></script>
	<link rel="stylesheet" type="text/css" href="/js/toastr/toastr.css">
	<script type="text/javascript" src="/bootstrap/bootstrap-dialog/dist/js/bootstrap-dialog.min.js"></script>
	<link rel="stylesheet" type="text/css" href="/bootstrap/bootstrap-dialog/dist/css/bootstrap-dialog.min.css">
</head>

<body class="hold-transition skin-red sidebar-mini" >
  <!-- .box-body -->
                
                    <div class="box-header with-border">
                        <h3 class="box-title">商品类型模板管理</h3>
                    </div>

                    <div class="box-body">

                        <!-- 数据表格 -->
                        <div class="table-box">

                            <!--工具栏-->
                            <div class="pull-left">
                                <div class="form-group form-inline">
                                    <div class="btn-group">
                                        <button type="button" onclick="toInsert()" class="btn btn-default" title="新建" data-toggle="modal" data-target="#editModal" ><i class="fa fa-file-o"></i> 新建</button>
                                        <button type="button" class="btn btn-default" title="删除"><i class="fa fa-trash-o"></i> 删除</button>
                                       
                                        <button type="button" class="btn btn-default" title="刷新" onclick="window.location.reload();"><i class="fa fa-refresh"></i> 刷新</button>
                                    </div>
                                </div>
                            </div>
                            <div class="box-tools pull-right">
                                <div class="has-feedback">
							                  分类模板名称：<input  >									
									<button class="btn btn-default">查询</button>                                    
                                </div>
                            </div>
                            <!--工具栏/-->

			                  <!--数据列表-->
			                  <table id="dataList" class="table table-bordered table-striped table-hover dataTable">
<!--			                      <thead>-->
<!--			                          <tr>-->
<!--			                              <th class="" style="padding-right:0px">-->
<!--			                                  <input id="selall" type="checkbox" class="icheckbox_square-blue">-->
<!--			                              </th> -->
<!--										  <th class="sorting_asc">模板ID</th>-->
<!--									      <th class="sorting">分类模板名称</th>-->
<!--									      <th class="sorting">关联品牌</th>-->
<!--									      <th class="sorting">关联规格</th>									     -->
<!--									      <th class="sorting">扩展属性</th>													     						-->
<!--					                      <th class="text-center">操作</th>-->
<!--			                          </tr>-->
<!--			                      </thead>-->
<!--			                      <tbody>-->
<!--			                          <tr>-->
<!--			                              <td><input  type="checkbox"></td>			                              -->
<!--				                          <td>1</td>-->
<!--									      <td>手机</td>-->
<!--									      <td>联想,华为,中兴</td>-->
<!--									      <td>网络制式</td>									 -->
<!--									      <td></td>		                                                                  -->
<!--		                                  <td class="text-center">                                           -->
<!--		                                 	  <button type="button" class="btn bg-olive btn-xs" data-toggle="modal" data-target="#editModal" >修改</button>                                           -->
<!--		                                  </td>-->
<!--			                          </tr>-->
<!--									  <tr>-->
<!--			                              <td><input  type="checkbox"></td>			                              -->
<!--				                          <td>2</td>-->
<!--									      <td>服装</td>-->
<!--									      <td>七匹狼,雅戈尔</td>-->
<!--									      <td>服装尺码</td>									 -->
<!--									      <td></td>		                                                                  -->
<!--		                                  <td class="text-center">                                           -->
<!--		                                 	  <button type="button" class="btn bg-olive btn-xs" data-toggle="modal" data-target="#editModal" >修改</button>                                           -->
<!--		                                  </td>-->
<!--			                          </tr>-->
<!--			                      </tbody>-->
			                  </table>
			                  <!--数据列表/-->                        
							  
							 
                        </div>
                        <!-- 数据表格 /-->
                        
                        
                        
                        
                     </div>
                    <!-- /.box-body -->
                    
	           
					    
                                
<!-- 编辑窗口 -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" >
	<div class="modal-content">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			<h3 id="myModalLabel">商品类型模板编辑</h3>
		</div>
		<div class="modal-body">

			<table class="table table-bordered table-striped"  width="100%">
		      	<tr>
		      		<td>商品类型</td>
		      		<td><input name="name"  class="form-control" placeholder="商品类型">  </td>
		      	</tr>
		      	<tr>
		      		<td>关联品牌</td>
		      		<td>
		      			<select id="brandSelect" name="brandIds" multiple style="width: 100%">
							<option  th:each="b:${brandList}" th:value="${b.id}">[[${b.name}]]</option>
						</select>
		      		</td>
		      	</tr>
		      	<tr>
		      		<td>关联规格</td>
		      		<td>
						<select id="specIdSelect" name="specIds" multiple style="width: 100%">
							<option id="specificationSelect" th:each="s:${specificationList}" th:value="${s.id}">[[${s.specName}]]</option>
						</select>
		      		</td>
		      	</tr>

		      	<tr>
		      		<td>扩展属性</td>
		      		<td>
		      			<div class="btn-group">
                             <button type="button" onclick="addTypeRow()" class="btn btn-default" title="新增扩展属性"><i class="fa fa-file-o"></i> 新增扩展属性</button>
                        </div>
						<table id="tab" class="table table-bordered table-striped"  width="800px">
							<thead>
								<tr>
								    <td><input type="checkbox" class="icheckbox_square-blue"></td>
									<td>属性名称</td>
									<td>操作</td>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td><input type="checkbox" class="icheckbox_square-blue" ></td>
									<td><input name="customAttributeItems" class="form-control" placeholder="属性名称" ></td>
									<td><button type="button" onclick="dele(this)" class="btn btn-default" title="删除"><i class="fa fa-trash-o"></i> 删除</button></td>
								</tr>
							</tbody>
						</table>

		      		</td>
		      	</tr>

			 </table>

		</div>
		<div class="modal-footer">
			<button id="preservation" onclick="insertGet()" class="btn btn-success" data-dismiss="modal" aria-hidden="true">保存</button>
			<button id="upadte" onclick="updateGet()" class="btn btn-success" data-dismiss="modal" aria-hidden="true">修改</button>
			<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
		</div>
	  </div>
	</div>
</div>
    
</body>
<script type="text/javascript">
	$(function () {
		$("#brandSelect").select2();
		$("#specIdSelect").select2();
	})
	$('#dataList').bootstrapTable({
		url: "/typeTemplate/selectInfoLimitServer", //请求后台的URL（*）
		method: 'get',                      //请求方式（*）
		// contentType: "application/x-www-form-urlencoded",/*使用post*/
		// toolbar: '#sdfname',              //工具按钮用哪个容器
		striped: true,                      //是否显示行间隔色
		cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
		pagination: true,                   //是否显示分页（*）
		sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
		pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
		pageSize: 5,                        //每页的记录行数（*）
		pageList: [1, 3, 5],                //可供选择的每页的行数（*）
		showColumns: true,                  //是否显示所有的列（选择显示的列）
		showRefresh: true,                  //是否显示刷新按钮
		minimumCountColumns: 1,             //最少允许的列数
		clickToSelect: true,                //是否启用点击选中行
		showToggle: true,                   //是否显示详细视图和列表视图的切换按钮
		detailView: true,                  //是否显示父子表
		//得到查询的参数
		queryParams : function (params) {
			//这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
			var temp = {
				pageSize: params.limit,
				//页面大小
				pageNumber: (params.offset / params.limit) + 1 ,  //页码
			};
			return temp;
		},
		columns: [{
			checkbox: true,
			visible: true                  //是否显示复选框
		}, {
			field: 'id',
			title: '模板ID'
		}, {
			field: 'name',
			title: '分类模板名称'
		},{
			field: 'specIds',
			title: '关联品牌',
			formatter:function (value, row, index) {
				var specId =  JSON.parse(value);
				var specName = "";
				for (var i = 0; i < specId.length; i++) {
					specName += specId[i].text + ",";
				}
				return specName.substring(0,specName.length -1);
			}
		},{
			field: 'brandIds',
			title: '关联规格',
			formatter:function (value, row, index) {
				var brandId =  JSON.parse(value);
				var brandName = "";
				for (var i = 0; i < brandId.length; i++) {
					brandName += brandId[i].text + ",";
				}
				return brandName.substring(0,brandName.length -1);
			}
		},{
			field: 'customAttributeItems',
			title: '扩展属性',
			formatter:function (value, row, index) {
				var item =  JSON.parse(value);
				var customAttributeItem = "";
				for (var i = 0; i < item.length; i++) {
					customAttributeItem += item[i].text + ",";
				}
				return customAttributeItem.substring(0,customAttributeItem.length -1);
			}
		},{
			field:'id',
			title: '操作',
			width: 120,
			align: 'center',
			valign: 'middle',
			formatter: function (value, row, index) {
				var id = value;
				var result = "";
				result += '<button type="button" onclick="updateType('+id+')" class="btn bg-olive btn-xs" data-toggle="modal" data-target="#editModal" >修改</button>  ';
				result += "<a href='javascript:DeleteById(" + id + ")' class='btn btn-xs red' title='删除'><span class='glyphicon glyphicon-remove'></span></a>";
				return result;
			}
		}
		],
		onLoadError: function () {
			toastr.error("数据加载失败！");
		},onDblClickRow: function (row, $element) {//双击事件
		}
	})
	/*查询*/
	function query() {
		$("#dataList").bootstrapTable("refresh");
	}
	function  addTypeRow(){
		var tab = document.getElementById("tab");
		//alert(tab.rows.length)
		var rownum = tab.rows.length;// 行数
		var newRow=tab.insertRow(rownum);

		var htmlTab = newRow.insertCell(0);
		var html  = "";
		html  +='<td><input type="checkbox" class="icheckbox_square-blue" ></td>';
		html  += '<td><input class="form-control" name="customAttributeItems" placeholder="属性名称" ></td>';
		html  += '<td><button type="button" onclick="dele(this)" class="btn btn-default" title="删除"><i class="fa fa-trash-o"></i> 删除</button></td>';
		newRow.innerHTML = html;
	}
	function dele(obj){
		var otr = obj.parentNode.parentNode;
		var tab =  otr.parentNode; //自己的父节点 就是table
		tab.removeChild(otr);
	}
	function toInsert() {
		$("#upadte").hide();
		$("#preservation").show();
	}
	/*添加*/
	function insertGet() {
		var brandIds = $("#brandSelect").select2("data");
		var brandList = [];
		for (var i = 0; i < brandIds.length; i++) {
			var  brand = {id:brandIds[i].id,text:brandIds[i].text};
			brandList.push(brand);
		}
		var list = JSON.stringify(brandList);
		var name = $("[name='name']").val();
		var specId = $("#specIdSelect").select2("data");
		var specs = [];
		for (var j = 0; j < specId.length; j++) {
			var  spec = {id:specId[j].id,text:specId[j].text};
			specs.push(spec);
		}
		var specIds = JSON.stringify(specs)

		var customAttributeItem = [];
		$("input[name='customAttributeItems']").each(function () {
			var Item = {text:$(this).val()};
			customAttributeItem.push(Item);
		});
		customAttributeItem = JSON.stringify(customAttributeItem);
		$.ajax({
			url:"/typeTemplate/addTypeTemplate",
			type:"post",
			dataType:"json",
			data:{
				name:name,
				specIds:specIds,
				brandIds:list,
				customAttributeItems:customAttributeItem
			},
			async:true,
			success:function (result) {
				if (result.code == 10000){
					$("#dataList").bootstrapTable("refresh",{pageNumber:1});
					toastr.success("成功");
				}else if (result.code==9999){
					toastr.error("失败");
				}
			},
			error:function (result) {
				toastr.error("错误");
			}
		})
	}
	/*修改*/
	function updateType(id) {
		$("#preservation").hide();
		$("#upadte").show();
		/*回显*/
		$.ajax({
			url:"/typeTemplate/getUpdateTypeTemplate/" + id,
			type:"post",
			dataType:"json",
			data:{},
			async:true,
			success:function (result) {
				if (result.code == 10000){
					$("[name='name']").val(result.data.name);
					var brandJson = result.data.brandIds;
					//将brandJson转为json类型
					var brandList = JSON.parse(brandJson);
					/*获取规格id*/
					var ids = [];
					for (var i = 0; i < brandList.length; i++) {
						ids.push(brandList[i].id);
					}
					$("#brandSelect").val(ids).trigger('change');
					/*获取品牌id*/
					var specJson = JSON.parse(result.data.specIds);
					var sId = [];
					for (var j = 0; j < specJson.length; j++) {
						sId.push(specJson[j].id);
					}
					$("#specIdSelect").val(sId).trigger('change');
					/*替换id=tab标签下的内容*/
					var Items = JSON.parse(result.data.customAttributeItems);
					console.log(Items);
					var htmlTab = "";
					htmlTab += '<thead><tr><td><input type="checkbox" class="icheckbox_square-blue"></td>' +
							'<input type="hidden" name="id" value="'+result.data.id+'">' +
							'<td>属性名称</td><td>操作</td></tr></thead>';
					for (var l = 0; l < Items.length; l++) {
						htmlTab += '<tbody><tr>';
						htmlTab += '<td><input type="checkbox" class="icheckbox_square-blue" ></td>';
						htmlTab += '<td><input name="customAttributeItems" value="'+Items[l].text+'" class="form-control" placeholder="属性名称" ></td>';
						htmlTab += '<td><button type="button" onclick="dele(this)" class="btn btn-default" title="删除"><i class="fa fa-trash-o"></i> 删除</button></td>';
						htmlTab += '</tr>';
						htmlTab += '</tbody>';
					}
					$("#tab").html(htmlTab);
				}
			},error:function (result) {
				console.log(result);
			}
		})
	}
	/*执行修改*/
	function updateGet() {
		var brandIds = $("#brandSelect").select2("data");
		var brandList = [];
		for (var i = 0; i < brandIds.length; i++) {
			var  brand = {id:brandIds[i].id,text:brandIds[i].text};
			brandList.push(brand);
		}
		var list = JSON.stringify(brandList);
		var name = $("[name='name']").val();
		var specId = $("#specIdSelect").select2("data");
		var specs = [];
		for (var j = 0; j < specId.length; j++) {
			var  spec = {id:specId[j].id,text:specId[j].text};
			specs.push(spec);
		}
		var specIds = JSON.stringify(specs)

		var customAttributeItem = [];
		$("input[name='customAttributeItems']").each(function () {
			var Item = {text:$(this).val()};
			customAttributeItem.push(Item);
		});
		customAttributeItem = JSON.stringify(customAttributeItem);
		$.ajax({
			url:"/typeTemplate/updateTypeTemplate/",
			type:"post",
			dataType:"json",
			data:{
				id:$("[name='id']").val(),
				name:name,
				specIds:specIds,
				brandIds:list,
				customAttributeItems:customAttributeItem
			},
			async:true,
			success:function (result) {
				$("#dataList").bootstrapTable("refresh",{pageNumber:1});
				toastr.success("成功");
			},error:function (result) {
				alert("错误");
			}
		})
	}
	/*删除*/
	function DeleteById(id) {
		var titleName = "删除";
		if (confirm("确定要删除吗?")) {
			$.ajax({
				url: "/typeTemplate/deleteTypeTemplate/" + id,
				type: "post",
				dataType: "json",
				data: {},
				async: false,
				success: function (result) {
					if (result.code == 10000) {
						toastr.success(result.message);
						$("table").bootstrapTable("refresh", {pageNumber: 1});
					} else {
						toastr.error(result.message);
					}
				},
				error: function (result) {
					toastr.error("错误");
				}
			})
		}
	}
</script>
</html>